// KeyParser.cpp: implementation of the CKeyParser class.
//
//////////////////////////////////////////////////////////////////////


#include "define.h"
#include "KeyParser.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CKeyParser::CKeyParser()
{
	Reset();
}

CKeyParser::~CKeyParser()
{

}
//----------------------------------------------------------------------------//



void CKeyParser::Reset()
{
	m_isBody = false;
	
	m_nHeaderKey = 0;
	
	m_nTotalPacketSize = 0;
	m_nCurPacketPnt = 0;
	
	
	m_nBodyKey = 0;
	m_nBodySize = 0;
}

int CKeyParser::MakePacket( char* szMsg, size_t nLen, char* szPacket, size_t& nPacketSize )
{	
	nPacketSize = 0;

	size_t nTotalSize = 0;	
	nTotalSize = nLen+sizeof(nTotalSize);
	
	size_t nBodySize = nLen;
	
	int nHeaderKey = MAKE_KEY( HEADER_KEY, nTotalSize );
	int nBodyKey = MAKE_KEY( BODY_KEY, nBodySize );
	
	memcpy( szPacket, &nHeaderKey, sizeof(nHeaderKey) );	
	
	memcpy( szPacket + sizeof(nHeaderKey), &nBodyKey, sizeof(nBodyKey) );
		
	memcpy( szPacket + sizeof(nHeaderKey) + sizeof(nBodyKey), szMsg, nLen );
	nPacketSize += sizeof(nHeaderKey) + sizeof(nBodyKey) + nLen ;

	return 0;
}


int CKeyParser::PacketParse( char* szMsg, size_t nLen, char* szPacket, size_t& nPacketSize  )
{
	size_t nBuffLength = 0;	
	
	while( nBuffLength < nLen )
	{
		if( m_isBody  )
		{			
			m_szRecvBuff[m_nCurPacketPnt] = szMsg[nBuffLength];
			m_nCurPacketPnt++;
			nBuffLength++;

			if( m_nTotalPacketSize == m_nCurPacketPnt )
			{
				memcpy( &m_nBodyKey, m_szRecvBuff, sizeof(int) );
				if( BODY_KEY != GET_BODY_KEY(m_nBodyKey) )
					return -2;
				
				m_nBodySize = GET_BODY_VALUE(m_nBodyKey);
				
				// PacketBind( m_szRecvBuff + sizeof(int), m_nBodySize );
				// func( m_szRecvBuff + sizeof(int), m_nBodySize );
				
				memcpy( szPacket, m_szRecvBuff + sizeof(int), m_nBodySize );
				nPacketSize += m_nBodySize;				
				
				PacketBind( szPacket, nPacketSize );

				Reset();
			}
			
		}
		else
		{
			
			memcpy( &m_nHeaderKey, szMsg+nBuffLength, sizeof(int)  );
			nBuffLength +=  sizeof(int);			
			
			if( HEADER_KEY != GET_HEADER_KEY(m_nHeaderKey) )
				continue;
			
			m_nTotalPacketSize = GET_HEADER_VALUE(m_nHeaderKey);
			m_nCurPacketPnt = 0;
			m_isBody = true;
		}
	}

	return -1;
}

int CKeyParser::PacketBind( char* szMsg, size_t nLen )
{
	
	int a = 10;
	
	return 0;
}
